<template>
  <div class="app-container" v-loading="loading" element-loading-text="数据加载中" element-loading-spinner="el-icon-loading">
    <el-form :model="queryParams.condition" ref="queryForm" size="small" :inline="true" v-show="showSearch"
      label-width="100px">
      <el-form-item label="检验单编号" prop="iqcCode">
        <el-input v-model="queryParams.condition.iqcCode" placeholder="请输入送检单号" clearable />
      </el-form-item>
      <el-form-item label="供应商" prop="vendorName">
        <el-input v-model="queryParams.condition.vendorName" placeholder="请输入供应商名称" clearable />
      </el-form-item>
      <el-form-item label="检验状态" prop="FQCStatus">
        <el-select v-model="queryParams.condition.FQCStatus" placeholder="请选择检验状态" clearable :style="{ width: '100%' }">
          <el-option v-for="(item, index) in fqcstatusOptions" :key="index" :label="item.label" :value="`${item.value}`"
            :disabled="item.disabled"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="物料编码" prop="itemCode">
        <el-input v-model="queryParams.condition.itemCode" placeholder="请输入物料编码" clearable />
      </el-form-item>
      <el-form-item label="收料通知单" prop="fbillno">
        <el-input v-model="queryParams.condition.fbillno" placeholder="请输入收料通知单" clearable />
      </el-form-item>
      <el-form-item label="检验日期">
        <el-date-picker v-model="queryParams.condition.params" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" @click="exportExcel"
          v-hasPermi="['mes:qc:iqc:export']">导出</el-button>
        <el-button type="primary" plain size="mini" icon="el-icon-share" @click="handleSerial">打印序列号</el-button>
        <el-button type="primary" plain size="mini" icon="el-icon-share" @click="batchNumber">打印批次号</el-button>
        <el-input-number :min="1" v-model="printNum" placeholder="打印张数" />
        <el-button style="margin-left: 10px" size="mini" type="danger" icon="el-icon-delete" @click="handleDelete()"
          v-hasPermi="['mes:qc:iqc:remove']">批量删除</el-button>
      </el-form-item>
    </el-form>
    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="exportExcel">导出</el-button>
      </el-col>
    </el-row>-->
    <!--   :span-method="listMethod" -->
    <el-table :data="iqcList" @selection-change="handleSelectionChange" height="calc(100vh - 230px)"
      :header-cell-style="{ fontSize: '14px', padding: '0px' }"
      :cell-style="{ fontSize: '14px', padding: '0px', lineHeight: '20px' }">
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="序号" align="center" width="50px" prop="issueCode">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检验单编号" width="150px" align="center" prop="iqcCode"></el-table-column>
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="送检单号" width="150px" align="center" prop="iqcCode" /> -->
      <el-table-column label="收料通知单号" align="center" width="120px" prop="fbillno" />
      <el-table-column label="批次号" align="center" width="120px" prop="batchCode">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="viewDetail(scope.row)">{{
            scope.row.batchCode
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="检验结果" width="80px" align="center" prop="checkResult">
        <template slot-scope="scope">
          <div :style="{ color: scope.row.checkResult == '0' ? 'red' : 'green' }">
            {{
              scope.row.checkResult == "0"
                ? "不合格"
                : scope.row.checkResult == "1"
                  ? "合格"
                  : ""
            }}
          </div>
        </template>
      </el-table-column>



      <el-table-column label="物料入库单号" align="center" width="120px" prop="recptCode" />
      <el-table-column label="供应商" width="150px" align="center" prop="vendorName" />
      <el-table-column label="状态" width="80px" align="center" prop="fqcstatus">
        <template slot-scope="scope">
          <div :style="{ color: scope.row.fqcstatus == '0' ? 'orange' : '' }">
            {{
              scope.row.fqcstatus == "0"
                ? "未检验"
                : scope.row.fqcstatus == "1"
                  ? "已检验"
                  : scope.row.fqcstatus == "2"
                    ? "已提交"
                    : "--"
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="物料编码" width="100px" align="center" prop="itemCode">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleViewItem(scope.row)">{{ scope.row.itemCode }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="物料名称" width="100px" align="center" prop="itemName" />
      <el-table-column label="规格型号" width="150px" align="center" prop="specification" />
      <el-table-column label="报检数量" width="80px" align="center" prop="quantityCheck" />
      <el-table-column label="创建时间" align="center" width="120px" prop="createTime" />

      <el-table-column label="检验开始时间" align="center" width="120px" prop="iqcInspectionTime" />
      <el-table-column label="检验结束时间" align="center" width="120px" prop="inspectDate" />
      <el-table-column label="检验时长" align="center" width="80px" prop="fbillno">
        <template slot-scope="scope">
          <span>{{
            timeDiff(scope.row.iqcInspectionTime, scope.row.inspectDate)
          }}</span>
        </template>
      </el-table-column>

      <el-table-column label="检验员" width="100px" align="center" prop="inspector" />

      <el-table-column label="抽检数量" width="80px" align="center" prop="quantitySpotCheck" />
      <el-table-column label="合格数量" width="80px" align="center" prop="receiveQty" />
      <el-table-column label="不合格数量" width="100px" align="center" prop="quantityUnqualified" />
      <!-- <el-table-column label="检验时间" width="120px" align="center" prop="inspectDate" /> -->
      <!-- <el-table-column label="审核员" width="120px" align="center" prop="auditor"/> -->
      <!-- <el-table-column label="审核时间" width="120px" align="center" prop="auditDate"/> -->
      <el-table-column label="操作" align="center" width="140px" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.fqcstatus == '0'"
            @click="handleView(scope.row)">检验</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.fqcstatus=='2'"
            @click="handleAdjustment(scope.row)"
          >调整</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.fqcstatus == '1'"
            @click="handleUpdate(scope.row)" v-hasPermi="['mes:qc:iqc:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit"
            v-if="scope.row.fqcstatus == '1' && scope.row.checkResult != '0'"
            @click="handlePushDown(scope.row)">下推</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.checkResult == '0'"
            @click="handleAbnormal(scope.row)">异常提报</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.fqcstatus == '2'"
            @click="handleRevocation(scope.row)">撤回</el-button>
          <el-button size="mini" type="text" icon="el-icon-view"
            v-if="scope.row.fqcstatus == '2' || scope.row.fqcstatus == '3'"
            @click="viewReport(true, scope.row)">查看报表</el-button>
          <el-button size="mini" type="text" icon="el-icon-share" @click="handlePrint(scope.row)"
            v-if="scope.row.recptCode != null">打印条码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows"
      :page-sizes="[10, 40, 80, 100, 200]" @pagination="getList" />

    <!-- 检验页面 -->
    <el-drawer :title="title" :visible.sync="open" size="90%" :before-close="cancel" custom-class="demo-drawer"
      :destroy-on-closey="true">
      <div class="demo-drawer__content dialogContent" style="padding: 0 20px">
        <el-form ref="form" :model="form" :rules="rules" label-width="auto">
          <el-row>
            <el-col :span="6">
              <el-form-item label="物料编码:" prop="itemCode">
                <el-input v-model="form.itemCode" placeholder :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物料名称:" prop="itemName">
                <el-input v-model="form.itemName" placeholder :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="规格型号:" prop="specification">
                <el-input v-model="form.specification" placeholder :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="报检单号:" prop="iqcCode">
                <el-input v-model="form.iqcCode" placeholder :disabled="true" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="6">
              <el-form-item label="供应商:" prop="vendorName">
                <el-input v-model="form.vendorName" placeholder :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="报检数量:" prop="quantityCheck">
                <el-input v-model="form.quantityCheck" placeholder :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检验时间:" prop="inspectDate">
                <el-date-picker clearable v-model="form.inspectDate" type="date" value-format="yyyy-MM-dd"
                  placeholder="请选择检验日期"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="抽样数量" prop="quantitySpotCheck">
                <el-input-number :controls="false" v-model="form.quantitySpotCheck" :max="form.quantityCheck" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="合格数量:" prop="receiveQty">
                <el-input v-model="form.receiveQty" placeholder @change="(value) =>
                  autoInput(value, 'receiveQty', 'quantityUnqualified')
                " />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="不合格数量:" prop="quantityUnqualified">
                <el-input v-model="form.quantityUnqualified" placeholder @change="(value) =>
                  autoInput(value, 'quantityUnqualified', 'receiveQty')
                " />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="质检方案" prop="InspectionScheme">
                <el-select v-model="form.InspectionScheme" filterable placeholder="请选择" @change="InspectionChange">
                  <el-option v-for="item in InspectionSchemeList" :key="item.fid" :label="item.fname"
                    :value="item.fid" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6" v-if="optType == 'edit'">
              <el-form-item label="SQE审核原因:" prop="sqeAuditReason">
                <el-input v-model="form.sqeAuditReason" placeholder disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="optType == 'edit'">
              <el-form-item label="品质部审核原因:" prop="pzbAuditReason">
                <el-input v-model="form.pzbAuditReason" placeholder disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 中间的table -->
          <el-row>
            <el-table v-loading="loading1" :data="templateList" :span-method="objectSpanMethod">
              <!-- <el-table-column type="index" label="序号" width="50" :index="indexMethod"></el-table-column> -->
              <el-table-column label="检查项目" align="center" prop="inspectionItem" width="140px" />
              <el-table-column label="缺陷等级" align="center" prop="defectLevel">
                <template slot-scope="scope">{{
                  scope.row.defectLevel == "1"
                    ? "A"
                    : scope.row.defectLevel == "2"
                      ? "B"
                      : "C"
                }}</template>
              </el-table-column>
              <el-table-column label="检验标准及检验方法" align="center" prop="inspectionStandard" width="260px" />
              <el-table-column label="检验方式及工具" align="center" prop="inspectionMethod" width="115px" />
              <el-table-column label="抽样标准" align="center" prop="samplingStandards" width="160px" />
              <el-table-column label="判定" align="center" prop="checkResult">
                <template slot-scope="scope">
                  <div class="headerDiv">
                    <span>Ac={{ scope.row.acceptQty }},</span>
                    <span>Re={{ scope.row.rejectQty }}</span>
                  </div>
                </template>
              </el-table-column>
              <!-- <el-table-column label="参考图片" align="center" prop="referenceImage" width="260px" /> -->
              <el-table-column label="检验记录" align="center" prop="analysisMethod" width="250px">
                <template slot-scope="scope">
                  <div class="headerDiv" v-if="scope.row.analysisMethod == '1'">
                    <!-- {{ scope.row.analysisMethod == "1"?"有比较值":"/"}} -->
                    <div style="text-align: left">
                      <span>目标值:</span>
                      <input v-model="scope.row.targetVal" style="width: 80px" @change="(e) => countChange(e, 'targetVal', scope.$index)
                      " />
                    </div>
                    <!-- <div>比较符{{ scope.row.compareSymbol == '1' ? '=' : '=' }}</div> -->
                    <div style="text-align: left">
                      <div style="text-align: left">
                        <span>
                          上偏差:
                          <input v-model="scope.row.upOffset" @change="(e) => countChange(e, 'upOffset', scope.$index)
                          " style="width: 60px" />
                        </span>
                        <span>
                          下偏差:
                          <input v-model="scope.row.downOffset" @change="(e) => countChange(e, 'downOffset', scope.$index)
                          " style="width: 60px" />
                        </span>
                      </div>
                      <span>
                        上限值:
                        <input v-model="scope.row.upLimit" style="width: 60px" />
                      </span>
                      <span>
                        下限值:
                        <input v-model="scope.row.downLimit" style="width: 60px" />
                      </span>
                    </div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column align="center" prop="checkResult" width="240px" label="检验结果">
                <template slot-scope="scope">
                  <div v-if="scope.row.analysisMethod == '1'">
                    实际值:
                    <input v-model="scope.row.actualValue" @input="(value) => inputActual(value, scope.$index)"
                      style="width: 80px" />
                    <!-- <input v-model="scope.row.actualValue" /> -->
                  </div>
                  <el-radio-group v-model="scope.row.checkResult" @input="checkChange">
                    <el-radio :label="1" :value="1">√</el-radio>
                    <el-radio :label="0" :value="0">×</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
            </el-table>
          </el-row>

          <el-form-item label="检验结果" prop="checkResult">
            <el-radio-group v-model="form.checkResult">
              <el-radio :label="1">√</el-radio>
              <el-radio :label="0">×</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item span="6" label="入库数量" prop="attr1">
            <el-input style="width: 150px" v-model="form.attr1" placeholder="请输入库数量" />
          </el-form-item>
          <el-form-item span="6" label="退料数量" prop="attr2">
            <el-input style="width: 150px" v-model="form.attr2" placeholder="请输入退料数量" />
          </el-form-item>

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注:" prop="remark">
                <el-input type="textarea" v-model="form.remark" placeholder="输入备注"
                  :autosize="{ minRows: 2, maxRows: 5 }" style="width: 450px; height: 100px"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <div style="margin-top: 20px" v-if="form.checkResult == 0">
            <el-form-item label="不合格品处理方式" prop="disposeType">
              <el-radio-group v-model="form.disposeType">
                <el-radio :label="0">返工/返修</el-radio>
                <el-radio :label="1">挑选</el-radio>
                <el-radio :label="2">让步</el-radio>
                <el-radio :label="3">退货</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- </el-col>
            <el-col :span="24">-->
            <el-form-item label="检验记录">
              <el-table :data="exceptionLogList">
                <el-table-column label="类型选择" align="center" prop="indexType">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.indexType" placeholder="请选择检测项目" clearable>
                      <el-option v-for="(dict, index) in abnormalList" :key="index" :label="dict" :value="dict" />
                    </el-select>
                  </template>
                </el-table-column>

                <el-table-column label="异常描述" align="center" prop="describeData">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.describeData" placeholder type="textarea" />
                  </template>
                </el-table-column>
                <el-table-column label="文件上传" align="center" prop="checkResult">
                  <template slot-scope="scope">
                    <ImageUpload :limit="1" :value="scope.row.fileName" :fileSize="15"
                      @input="(url) => handleImgUplaoded(url, scope.$index)"
                      @onRemoved="(url) => handleImgRemoved(url, scope.$index)"></ImageUpload>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button size="medium" type="text" icon="el-icon-circle-plus-outline"
                      @click="errorAdd()"></el-button>
                    <el-button v-if="scope.$index != 0" size="medium" type="text" icon="el-icon-remove-outline"
                      @click="errorDel(scope.$index)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <!-- </el-col>
            </el-row>-->
          </div>
        </el-form>
      </div>

      <div class="demo-drawer__footer" style="text-align: right">
        <el-button type="primary" @click="cancel" v-if="optType == 'view'">返回</el-button>
        <el-button type="primary" @click="submitForm" v-if="optType != 'ment' && optType != 'view'">确 定</el-button>
        <el-button type="primary" @click="submitForm" v-if="optType == 'ment'">调 整</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>

    <iqc-detail v-if="detailVisible" ref="detailOrUpdate"></iqc-detail>
    <Itemdetail v-if="openItem" ref="itemdetails"></Itemdetail>
    <BatchDetail ref="batchDetail"></BatchDetail>
    <!-- 2025-2-12 新增 异常提报 -->
    <AbnormalDetails ref="abnormalDetailsRef"></AbnormalDetails>
  </div>
</template>

<script>
import iqcDetail from "./iqc_detail.vue";
import { blobValidate } from "@/utils/hici";
import { Message, Loading } from "element-ui";
import { saveAs } from "file-saver";
import {
  listIqc,
  getIqc,
  delIqc,
  addIqc,
  updateIqc,
  getinspectData,
  submitQcIqc,
  listIqcHead,
  getDetail,
  editQcIqcInfoDto,
  mentQcIqcInfoDto,
  pushDownQcIqcInfoDto,
  revocationQcIqc,
  qcschemeAll,
  qcscheme,
  getSnCode,
  getBanthNo,
  handleExport,
  handleDeleteList,
} from "@/api/mes/qc/iqc";
import {
  getItemRecptItems,
  printItem,
  batchItem,
} from "@/api/mes/wm/itemrecpt";
import ItemSelect from "@/components/itemSelect/single.vue";
import VendorSelect from "@/components/vendorSelect/single.vue";
import IqcLine from "./iqcline.vue";
import { genCode } from "@/api/mes/md/rule";
import { getReport, getReport2 } from "@/api/mes/report/report";
import { addItemrecpt, addItemrecptData } from "@/api/mes/wm/itemrecpt";
import Itemdetail from "../../md/mditem/components/itemDetail.vue";
import BatchDetail from "./batch_detail.vue";
import moment from "moment";
import AbnormalDetails from "./components/abnormalDetails.vue";
let downloadLoadingInstance;
export default {
  name: "IqcIndex",
  dicts: ["mes_qc_result", "mes_order_status"],
  components: {
    ItemSelect,
    VendorSelect,
    IqcLine,
    iqcDetail,
    Itemdetail,
    BatchDetail,
    AbnormalDetails
  },
  data() {
    return {
      //打印张数
      printNum: 1,
      wmItemRecptItemList2: [],
      //自动生成编码
      autoGenFlag: false,
      optType: undefined,
      acceptImg: require("@/assets/images/accept.png"),
      rejectImg: require("@/assets/images/reject.png"),
      prepareImg: require("@/assets/images/prepare.png"),
      // 遮罩层
      loading: true,
      openItem: false,
      contrastList: [
        { min: 0, max: 1, value: 1 },
        { min: 2, max: 8, value: 2 },
        { min: 9, max: 15, value: 3 },
        { min: 16, max: 25, value: 5 },
        { min: 26, max: 50, value: 8 },
        { min: 51, max: 90, value: 13 },
        { min: 91, max: 150, value: 20 },
        { min: 151, max: 280, value: 32 },
        { min: 281, max: 500, value: 32 },
        { min: 501, max: 1200, value: 125 },
        { min: 1201, max: 3200, value: 125 },
        { min: 3201, max: 10000, value: 200 },
      ],
      // 选中数组
      ids: [],
      status: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      showFlag: false,
      // 总条数
      total: 0,
      // 来料检验单表格数据
      iqcList: [
        {
          inspectionNo: "1145522",
        },
      ],
      fqcstatusOptions: [
        {
          label: "未检验",
          value: 0,
        },
        {
          label: "已检验",
          value: 1,
        },
        {
          label: "已提交",
          value: 2,
        },
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        page: 1,
        rows: 10,
        condition: {
          iqcCode: null,
          vendorName: null,
          FQCStatus: null,
          itemCode: null,
          inspectDate: null,
          params: [],
          fbillno: null,
        },
      },
      // 表单参数
      form: {},
      // 模板列表
      templateList: [],
      loading1: false,
      // 不合格数
      failedSncode: [],
      //质检方案
      InspectionSchemeList: [],
      // 序列码集合
      snObj: {},
      //异常列表
      abnormalList: [],
      // 表单校验
      rules: {
        iqcCode: [
          {
            required: true,
            message: "来料检验单编号不能为空",
            trigger: "blur",
          },
        ],
        iqcName: [
          {
            required: true,
            message: "来料检验单名称不能为空",
            trigger: "blur",
          },
        ],

        vendorCode: [
          { required: true, message: "供应商不能为空", trigger: "blur" },
        ],
        itemCode: [
          { required: true, message: "物料不能为空", trigger: "blur" },
        ],
        receiveQty: [
          { required: true, message: "请输入合格数量", trigger: "blur" },
        ],
        quantityCheck: [
          { required: true, message: "本次检测数量不能为空", trigger: "blur" },
        ],
        quantityUnqualified: [
          { required: true, message: "请输入不合格数量", trigger: "blur" },
        ],
        inspectDate: [
          { required: true, message: "清选择检验日期", trigger: "change" },
        ],
      },
      //详情页面
      detailVisible: false,
      exceptionLogList: [{}],
      spanArr: [],
      // spanArr1:[],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    viewDetail(row) {
      console.log(124, this.$refs.batchDetail);
      this.$nextTick(() => {
        this.$refs.batchDetail.init(row);
      });
    },
    //批量打印批次号
    batchNumber() {
      if (this.ids && this.ids.length) {
        this.loading = true
        getBanthNo(this.ids)
          .then((response) => {
            if (response.code === 200) {
              console.log(1111, response);
              this.wmItemRecptItemList2 = response.data || [];
              if (this.wmItemRecptItemList2.length) {
                var addList = [];
                this.wmItemRecptItemList2.forEach((el) => {
                  addList.push(el);
                });
                for (var i = 1; i < this.printNum; i++) {
                  this.wmItemRecptItemList2.forEach((el) => {
                    addList.push(el);
                  });
                }
                this.$modal
                  .confirm('是否确认打印物料编号为"' + this.ids + '"的数据项？')
                  .then(() => {
                    return batchItem(addList);
                  })
                  .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("打印成功");
                  })
                  .catch(() => {
                    // 处理异常情况
                    console.error("打印出错");
                  });
                this.loading = false
              } else {
                this.loading = false
                this.$message.warning("没查到打印参数！");
              }
            } else {
              this.loading = false
              // 处理接口返回的错误信息
              console.error("接口调用失败:", response.message);
            }
          })
          .catch((error) => {
            this.loading = false
            // 处理异常情况
            console.error("接口调用异常:", error);
          });
      } else {
        this.$message.warning("请先选择需要打印的数据！");
      }
    },
    handleSerial() {
      if (this.ids && this.ids.length) {
        this.loading = true
        getSnCode(this.ids).then((res) => {
          console.log(res, "打印前需要调的接口res");
          if (res.code === 200) {
            this.wmItemRecptItemList = res.data ? res.data : [];
            if (this.wmItemRecptItemList.length) {
              var addList = [];
              this.wmItemRecptItemList.forEach((el) => {
                addList.push(el);
              });
              for (var i = 1; i < this.printNum; i++) {
                this.wmItemRecptItemList.forEach((el) => {
                  addList.push(el);
                });
              }
              this.$modal
                .confirm('是否确认打印物料编号为"' + this.ids + '"的数据项？')
                .then(() => {
                  return printItem(addList);
                })
                .then(() => {
                  this.getList();
                  this.$modal.msgSuccess("打印成功");
                })
                .catch(() => {
                  // 处理异常情况
                  console.error("打印出错");
                });
              this.loading = false
            } else {
              this.loading = false
              this.$message.warning("请先选择需要打印的数据！");
            }
          } else {
            this.loading = false
            // 处理接口返回的错误信息
            console.error("接口调用失败:", response.message);
          }
        });
      } else {
        this.$message.warning("请先选择需要打印的数据！");
      }
    },
    //批量删除
    handleDelete() {
      if (this.ids && this.ids.length) {
        //let teger = null;
        //this.status.forEach((item) => {
        //  if (item != 0) teger = 1;
        //});
        //if (teger)
        //  return this.$modal.msgError("勾选数据包含已检验数据，不可删除");
        this.loading = true
        this.$modal
          .confirm('是否确认删除编号为"' + this.ids + '"的数据项？')
          .then(() => {
            handleDeleteList(this.ids).then((res) => {
              if (res.code === 200) {
                this.$modal.msgSuccess("删除成功");
                this.getList();
              } else {
                // 处理接口返回的错误信息
                console.error("接口调用失败:", response.message);
              }
            });
            this.loading = false
          }).catch(() => {
            this.loading = false
          });
      } else {
        this.$message.warning("请先选择需要删除的数据！");
      }
    },
    /** 查询来料检验单列表 */
    getList() {
      this.loading = true;
      listIqcHead(this.queryParams).then((response) => {
        this.iqcList = response.data.datas;
        this.total = response.data.total;
        this.loading = false;
        this.getSpanArrList(response.data.rows || []);
      }).catch(() => {
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        iqcId: null,
        iqcCode: null,
        iqcName: null,
        templateId: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
        vendorBatch: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityMinCheck: null,
        quantityMaxUnqualified: null,
        quantityRecived: null,
        quantityCheck: null,
        quantityUnqualified: null,
        crRate: null,
        majRate: null,
        minRate: null,
        crQuantity: null,
        majQuantity: null,
        minQuantity: null,
        checkResult: null,
        reciveDate: null,
        inspectDate: null,
        inspector: null,
        status: "PREPARE",
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.autoGenFlag = false;
      this.snObj = {};
      this.templateList = [];
      this.optType = undefined;
      this.exceptionLogList = [];
      this.resetForm("form");
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 导出 */
    exportExcel() {
      let query = {
        fbillno: this.queryParams.condition.fbillno,
        vendorName: this.queryParams.condition.vendorName,
        iqcCode: this.queryParams.condition.iqcCode,
        FQCStatus: this.queryParams.condition.FQCStatus,
        itemCode: this.queryParams.condition.itemCode,
        startDate: this.queryParams.condition.params[0]
          ? this.queryParams.condition.params[0]
          : null,
        stopDate: this.queryParams.condition.params[1]
          ? this.queryParams.condition.params[1]
          : null,
      };
      this.download(
        "/mes/qc/iqcHead/export",
        {
          ...query,
        },
        `iqc_${new Date().getTime()}.xlsx`
      );
      // let query = {
      //   fbillno: this.queryParams.condition.fbillno,
      //   vendorName: this.queryParams.condition.vendorName,
      //   iqcCode: this.queryParams.condition.iqcCode,
      //   FQCStatus: this.queryParams.condition.FQCStatus,
      //   itemCode: this.queryParams.condition.itemCode,
      //   startDate: this.queryParams.condition.params[0]?this.queryParams.condition.params[0]:null,
      //   stopDate: this.queryParams.condition.params[1]?this.queryParams.condition.params[1]:null,
      // };
      // downloadLoadingInstance = Loading.service({
      //   text: "正在下载数据，请稍候",
      //   spinner: "el-icon-loading",
      //   background: "rgba(0, 0, 0, 0.7)",
      // });

      // handleExport(query)
      //   .then(async (data) => {
      //     console.log(1111,data)
      //     const isBlob = blobValidate(data);
      //     if (isBlob) {
      //       const blob = new Blob([data]);
      //       saveAs(blob, 'iqc检验列表' + `.xlsx`);
      //     } else {
      //       const resText = await data.text();
      //       const rspObj = JSON.parse(resText);
      //       const errMsg =
      //         errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
      //       Message.error(errMsg);
      //     }
      //     downloadLoadingInstance.close();
      //   })
      //   .catch((r) => {
      //     console.error(r);
      //     Message.error("下载文件出现错误，请联系管理员！");
      //     downloadLoadingInstance.close();
      //   });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.condition.params = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.iqcId);
      this.status = selection.map((item) => item.fqcstatus);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    //检验
    handleView(row) {
      console.log(row, "rows");
      this.loading1 = false;
      this.open = true;
      // 调用查询质检方案list接口
      this.getQualityinspection();
      this.form = { ...row };
      this.optType = "add";
      // 获取当前日期和时间格式化格式
      let currentDate = new Date();
      let formattedDate = currentDate
        .toISOString()
        .replace(/T/, " ")
        .replace(/\..+/, "");
      this.form.inspectDate = formattedDate;
      this.form.iqcInspectionTime = moment(currentDate).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      console.log(this.form, "========form========");
      getinspectData(this.form).then((res) => {
        console.log(res, "检查项检查内容dres");
        //add begin by zyj 2024/10/29 检验项默认合格 checkResult
        res.data.qcIqcInspectionItemList.forEach((item) => {
          if (item.analysisMethod != "1") {
            item.checkResult = 1;
          }
        });
        //add end by zyj 2024/10/29 检验项默认合格
        this.templateList = res.data.qcIqcInspectionItemList;
        this.getSpanArr(res.data.qcIqcInspectionItemList);
        this.abnormalList = this.templateList.map((item) => {
          return item.inspectionItem;
        });

        this.spotCheck();
      });
    },
    //调整
    handleAdjustment(row) {
      this.reset();
      getDetail(row).then((res) => {
        this.form = { ...res.data };
        console.log(this.form, "详情res");
        this.templateList = this.form.qcIqcInspectionItemList;
        //给序列号赋值
        this.exceptionLogList = this.form.failedSncode[0].exceptionLogList;
        this.getSpanArr(res.data.qcIqcInspectionItemList);
        this.open = true;
        this.optType = "ment";
        this.abnormalList = this.templateList.map((item) => {
          return item.inspectionItem;
        });
        //不合格处理方式的值转成number类型
        console.log(this.exceptionLogList, "=====this.exceptionLogList======");
      });
    },
    //查询质检方案list
    getQualityinspection() {
      qcschemeAll().then((res) => {
        console.log(res, "质检方案的list");
        if (res.code == 200) {
          this.InspectionSchemeList = res.data;
        }
      });
    },
    //质检方案下拉change事件
    InspectionChange(value) {
      console.log(value, "质检方案下拉change事件");
      let params = {
        fid: value,
        quantityCheck: this.form.quantitySpotCheck,
      };
      qcscheme(params).then((res) => {
        console.log(res, "根据id查询质检方案的res");
        //add begin by zyj 2024/10/29 检验项默认合格 checkResult
        res.data.qcIqcInspectionItemList.forEach((item) => {
          if (item.analysisMethod != "1") {
            item.checkResult = 1;
          }
        });
        //add begin by zyj 2024/10/29 检验项默认合格 checkResult
        this.templateList = res.data.qcIqcInspectionItemList;
        this.getSpanArr(res.data.qcIqcInspectionItemList);
        this.abnormalList = this.templateList.map((item) => {
          return item.inspectionItem;
        });

        this.spotCheck();
      });
    },
    //打印
    handlePrint(row) {
      console.log(row, "打印条码的row");
      getItemRecptItems(row.recptId)
        .then((response) => {
          console.log(response, "打印前需要调的接口res");
          if (response.code === 200) {
            this.wmItemRecptItemList = response.data;
            const recptCode = row.recptCode;
            this.$modal
              .confirm('是否确认打印物料编号为"' + recptCode + '"的数据项？')
              .then(() => {
                console.log(this.wmItemRecptItemList, "WmIssueLineList");
                return printItem(this.wmItemRecptItemList);
              })
              .then(() => {
                this.getList();
                this.$modal.msgSuccess("打印成功");
              })
              .catch(() => {
                // 处理异常情况
                console.error("打印出错");
              });
          } else {
            // 处理接口返回的错误信息
            console.error("接口调用失败:", response.message);
          }
        })
        .catch((error) => {
          // 处理异常情况
          console.error("接口调用异常:", error);
        });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getDetail(row).then((res) => {
        this.form = { ...res.data };
        console.log(this.form, "详情res");
        this.templateList = this.form.qcIqcInspectionItemList;
        //给序列号赋值
        this.exceptionLogList = this.form.failedSncode[0].exceptionLogList;
        this.getSpanArr(res.data.qcIqcInspectionItemList);
        this.open = true;
        this.optType = "edit";
        this.abnormalList = this.templateList.map((item) => {
          return item.inspectionItem;
        });
        //不合格处理方式的值转成number类型
        console.log(this.exceptionLogList, "=====this.exceptionLogList======");
      });
    },
    // 判断抽检数量
    spotCheck() {
      this.form.quantitySpotCheck = this.form.quantityCheck
        ? this.contrastList.filter((item) => {
          return (
            this.form.quantityCheck >= item.min &&
            this.form.quantityCheck <= item.max
          );
        })[0].value
        : 0;
    },
    // 判断当前是否是合格
    // checkChange(value) {
    //   let failedIndex = 0;
    //   let failedSncode = [];
    //   let qualifiedCode = 0;
    //   for (let i = 0; i < this.form.quantitySpotCheck; i++) {
    //     let str = "checkResult" + i;
    //     let bool = this.templateList.every(item => item[str] != 0);
    //     if (!bool) {
    //       // failedIndex++; //不合格数量
    //       failedSncode.push({
    //         // snCode: this.snObj[`snCode${i}`],
    //         exceptionLogList: [{}]
    //       });
    //     } else {
    //       qualifiedCode++; //合格数量
    //     }
    //   }
    //   // this.form.quantityUnqualified = failedIndex; //不合格数量
    //   // this.form.receiveQty = qualifiedCode; //合格数量
    //   // this.failedSncode = failedSncode;
    //   // this.form.checkResult = failedIndex === 0 ? 1 : 0;
    // },
    // 异常记录增加
    errorAdd() {
      let obj = {};
      this.exceptionLogList.push(obj);
    },
    // 删除异常记录
    errorDel(index) {
      this.exceptionLogList.splice(index, 1);
    },
    //图片上传成功
    handleImgUplaoded(imgUrl, index) {
      console.log(imgUrl, "=========");
      this.exceptionLogList[index].fileName = imgUrl;
      // this.form.sopUrl = imgUrl;
    },
    //图片移除
    handleImgRemoved(imgUrl, index) {
      console.log(imgUrl);
      this.exceptionLogList[index].fileName = null;
    },

    /** 提交按钮 */
    submitForm() {
      if (this.form.attr1 != null && this.form.attr1 > this.form.quantityCheck)
        return this.$message.error("入库数量不可大于保检数量");
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let params = {};
          params = { ...this.form };
          params.qcIqcInspectionItemList = this.templateList;
          let bool = false;
          for (let j = 0; j < this.templateList.length; j++) {
            const element = this.templateList[j].checkResult;
            console.log(element);
            if (element === undefined) {
              bool = true;
            }
          }
          if (bool) {
            this.$message({
              message: "请填写检验结果！！！",
              type: "warning",
            });
            return;
          }
          //检验结果和不合格检验方式等信息放在一个数组里
          console.log(this.failedSncode, "this.failedSncode");
          params.failedSncode = [
            {
              exceptionLogList: this.exceptionLogList,
              repairState: this.form.disposeType,
            },
          ];

          console.log(params, "params");
          if (this.optType == "add") {
            submitQcIqc(params).then((res) => {
              console.log(res, "提交的res");
              if (res.code == 200) {
                this.$modal.msgSuccess("提交成功");
                this.open = false;
                this.reset();
                // setTimeout(() => {
                //   this.getList();
                // }, 1001);
              } else {
                this.$modal.msgSuccess(res.msg);
              }
            });
          } else if (this.optType == "edit") {
            params.isUpdate = "1";
            editQcIqcInfoDto(params).then((res) => {
              console.log(res, "提交的res");
              if (res.code == 200) {
                this.$modal.msgSuccess("提交成功");
                this.open = false;
                this.reset();
                // setTimeout(() => {
                //   this.getList();
                // }, 1001);
                // this.getList();
              } else {
                this.$modal.msgSuccess(res.msg);
              }
            });
          } else if (this.optType == "ment") {
            mentQcIqcInfoDto(params).then((res) => {
              console.log(res, "调整的res");
              if (res.code == 200) {
                this.$modal.msgSuccess("调整成功");
                this.open = false;
                this.reset();
              } else {
                this.$modal.msgSuccess(res.msg);
              }
            });
          }
        } else {
          this.$message({
            message: "请填写完整信息!",
            type: "warning",
          });
        }
      });
      // this.$refs["form"].validate(valid => {
      //   if (valid) {
      //     if (this.form.iqcId != null) {
      //       updateIqc(this.form).then(response => {
      //         this.$modal.msgSuccess("修改成功");
      //         //this.open = false;
      //         this.getList();
      //       });
      //     } else {
      //       addIqc(this.form).then(response => {
      //         this.$modal.msgSuccess("新增成功");
      //         //this.open = false;
      //         this.form.iqcId=response.data;
      //         this.getList();
      //       });
      //     }
      //   }
      // });
    },
    // //生成采购入库单接口
    // handleAddpurchasewarehousing(row){
    //   const iqcId = row.iqcId || this.ids
    //   getIqc(iqcId).then(response => {
    //     this.form = response.data;
    //     addItemrecptData(this.form).then(response => {
    //       this.$modal.msgSuccess("生成采购入库单成功");
    //       this.getList();
    //     });
    //   });
    // },

    // 详情页面
    viewReport(isEdit, row) {
      this.detailVisible = true;
      this.$nextTick(() => {
        this.$refs.detailOrUpdate.init(isEdit, row);
      });
    },

    handleSelectProduct() {
      this.$refs.itemSelect.showFlag = true;
    },
    //物料选择弹出框
    onItemSelected(obj) {
      debugger;
      if (obj != undefined && obj != null) {
        this.form.itemId = obj.jdyItemId;
        this.form.itemCode = obj.itemCode;
        this.form.itemName = obj.itemName;
        this.form.specification = obj.specification;
        this.form.unitOfMeasure = obj.unitOfMeasure;
      }
    },
    handleSelectVendor() {
      this.$refs.vendorSelect.showFlag = true;
    },
    //供应商选择弹出框
    onVendorSelected(obj) {
      debugger;
      if (obj != undefined && obj != null) {
        this.form.vendorId = obj.vendorId;
        this.form.vendorCode = obj.vendorCode;
        this.form.vendorName = obj.vendorName;
        this.form.vendorNick = obj.vendorNick;
      }
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode("QC_IQC_CODE").then((response) => {
          this.form.iqcCode = response;
        });
      } else {
        this.form.iqcCode = null;
      }
    },
    // 行合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      console.log(rowIndex, "=====rowIndex======");
      if (columnIndex !== 6 && columnIndex !== 7) {
        const _row = this.spanArr1[rowIndex]; // 合并行数
        const _col = this.spanArr1[rowIndex] > 0 ? 1 : 0; // 合并的列数
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
      // if ( columnIndex !== 7) {
      //   const _row = this.spanArr1[rowIndex]; // 合并行数
      //   const _col = this.spanArr1[rowIndex] > 0 ? 1 : 0; // 合并的列数
      //   return {
      //     rowspan: _row,
      //     colspan: _col
      //   };
      // }
    },
    // 按照类型合并
    getSpanArr(data) {
      this.spanArr1 = []; // tip: 后台获取完成数据后，一定要重置spanArr=[],避免出现合并混乱！！！！！
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          // 当为第一行时
          if (i === 0) {
            this.spanArr1.push(1);
            this.pos = 0;
          } else {
            // 判断当前值是否与上一行的【名称】相等，相等则进行合并
            console.log(i, "=======i++====");
            if (
              data[i].inspectionStandard === data[i - 1].inspectionStandard &&
              data[i].inspectionItem === data[i - 1].inspectionItem
            ) {
              this.spanArr1[this.pos] += 1; // 合并单元格：合并的行数 +1
              this.spanArr1.push(0); // 0代表单元格是不需要显示, 已经被合并的单元格
            } else {
              this.spanArr1.push(1); // 1代表当前这行的数据需要被显示
              this.pos = i;
              console.log(this.spanArr1, "======");
            }
          }
        }
        console.log(this.spanArr1, "=====spanArr1=======");
      }
    },
    // 最外层列表合并
    // 行合并
    listMethod({ row, column, rowIndex, columnIndex }) {
      // for (let i = 1; i <= 3; i++) {
      if (columnIndex == 1) {
        const _row = this.spanArr[rowIndex]; // 合并行数
        const _col = this.spanArr[rowIndex] > 0 ? 1 : 0; // 合并的列数
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
      // }
    },
    // 按照类型合并
    getSpanArrList(data) {
      this.spanArr = []; // tip: 后台获取完成数据后，一定要重置spanArr=[],避免出现合并混乱！！！！！
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          // 当为第一行时
          if (i === 0) {
            this.spanArr.push(1);
            this.pos = 0;
          } else {
            // 判断当前值是否与上一行的【名称】相等，相等则进行合并
            if (data[i].iqcCode === data[i - 1].iqcCode) {
              this.spanArr[this.pos] += 1; // 合并单元格：合并的行数 +1
              this.spanArr.push(0); // 0代表单元格是不需要显示, 已经被合并的单元格
            } else {
              this.spanArr.push(1); // 1代表当前这行的数据需要被显示
              this.pos = i;
            }
          }
        }
      }
    },
    // 计算目标值
    countChange(e, type, i) {
      // targetVal upOffset  downOffset
      this.templateList[i].upLimit =
        Number(this.templateList[i].targetVal) +
        Number(this.templateList[i].upOffset);
      this.templateList[i].downLimit =
        Number(this.templateList[i].targetVal) -
        Number(this.templateList[i].downOffset);
    },
    inputActual(value, i) {
      console.log(value, i, "=====e========");
      console.log(this.templateList[i].downLimit, this.templateList[i].upLimit);
      if (
        Number(this.templateList[i].actualValue) >=
        this.templateList[i].downLimit &&
        Number(this.templateList[i].actualValue) <= this.templateList[i].upLimit
      ) {
        this.templateList[i].checkResult = 1;
      } else {
        this.templateList[i].checkResult = 0;
      }
      this.checkChange();
    },
    // 自动判断是否合格
    checkChange(value) {
      let str = "checkResult";
      let bool = this.templateList.every((item) => item[str] == 1);
      this.form.checkResult = bool ? 1 : 0;
      console.log(bool, this.exceptionLogList, "======");
      if (!bool && this.exceptionLogList.length == 0) {
        debugger;
        let obj = {};
        this.exceptionLogList.push(obj);
      }
    },

    // 下推

    handlePushDown(row) {
      this.loading = true
      let query = { ...row };
      this.$modal
        .confirm('是否确认下推检验单编号为"' + row.iqcCode + '"的数据项？')
        .then(function () {
          return pushDownQcIqcInfoDto(query);
        })
        .then(() => {
          this.loading = false
          this.getList();
          this.$modal.msgSuccess("下推成功");
        })
        .catch(() => { this.loading = false });
    },
    // 2025-2-12 新增异常提报
    handleAbnormal(row) {
      this.$nextTick(() => {
        this.$refs.abnormalDetailsRef.init(row);
      });
    },
    // 撤回
    handleRevocation(row) {
      let query = { ...row };
      this.$modal
        .confirm('是否确认撤回检验单编号为"' + row.iqcCode + '"的数据项？')
        .then(function () {
          return revocationQcIqc(query);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("撤回成功");
        })
        .catch(() => { });
    },
    // 自动计算合格不合格数量
    autoInput(e, type, name) {
      if (e > this.form.quantityCheck) {
        this.$message({
          message: "数量不允许超过报检数量！！！",
          type: "warning",
        });
        this.form[type] = 0;
      } else {
        this.form[name] = this.form.quantityCheck - this.form[type];
      }
      // this.form[name] =  this.form.quantityCheck - this.form[type]
    },
    handleViewItem(row) {
      this.openItem = true;
      this.$nextTick(() => {
        this.$refs.itemdetails.init(row, "mdItemId");
      });
    },
  },
};
</script>
